home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Library / Manuels & Misc / Zip / appnote.txt
Encoding:
Text File  |  2000-05-25  |  45.4 KB  |  1,169 lines

  1. Revised: 08/01/1998
  2.  
  3. Disclaimer
  4. ----------
  5.  
  6. Although PKWARE will attempt to supply current and accurate
  7. information relating to its file formats, algorithms, and the
  8. subject programs, the possibility of error can not be eliminated.
  9. PKWARE therefore expressly disclaims any warranty that the
  10. information contained in the associated materials relating to the
  11. subject programs and/or the format of the files created or
  12. accessed by the subject programs and/or the algorithms used by
  13. the subject programs, or any other matter, is current, correct or
  14. accurate as delivered.  Any risk of damage due to any possible
  15. inaccurate information is assumed by the user of the information.
  16. Furthermore, the information relating to the subject programs
  17. and/or the file formats created or accessed by the subject
  18. programs and/or the algorithms used by the subject programs is
  19. subject to change without notice.
  20.  
  21.  
  22. General Format of a ZIP file
  23. ----------------------------
  24.  
  25.   Files stored in arbitrary order.  Large zipfiles can span multiple
  26.   diskette media.
  27.  
  28.   Overall zipfile format:
  29.  
  30.     [local file header + file data + data_descriptor] . . .
  31.     [central directory] end of central directory record
  32.  
  33.  
  34.   A.  Local file header:
  35.  
  36.         local file header signature     4 bytes  (0x04034b50)
  37.         version needed to extract       2 bytes
  38.         general purpose bit flag        2 bytes
  39.         compression method              2 bytes
  40.         last mod file time              2 bytes
  41.         last mod file date              2 bytes
  42.         crc-32                          4 bytes
  43.         compressed size                 4 bytes
  44.         uncompressed size               4 bytes
  45.         filename length                 2 bytes
  46.         extra field length              2 bytes
  47.  
  48.         filename (variable size)
  49.         extra field (variable size)
  50.  
  51.  
  52.   B.  Data descriptor:
  53.  
  54.         crc-32                          4 bytes
  55.         compressed size                 4 bytes
  56.         uncompressed size               4 bytes
  57.  
  58.       This descriptor exists only if bit 3 of the general
  59.       purpose bit flag is set (see below).  It is byte aligned
  60.       and immediately follows the last byte of compressed data.
  61.       This descriptor is used only when it was not possible to
  62.       seek in the output zip file, e.g., when the output zip file
  63.       was standard output or a non seekable device.
  64.  
  65.   C.  Central directory structure:
  66.  
  67.       [file header] . . .  end of central dir record
  68.  
  69.       File header:
  70.  
  71.         central file header signature   4 bytes  (0x02014b50)
  72.         version made by                 2 bytes
  73.         version needed to extract       2 bytes
  74.         general purpose bit flag        2 bytes
  75.         compression method              2 bytes
  76.         last mod file time              2 bytes
  77.         last mod file date              2 bytes
  78.         crc-32                          4 bytes
  79.         compressed size                 4 bytes
  80.         uncompressed size               4 bytes
  81.         filename length                 2 bytes
  82.         extra field length              2 bytes
  83.         file comment length             2 bytes
  84.         disk number start               2 bytes
  85.         internal file attributes        2 bytes
  86.         external file attributes        4 bytes
  87.         relative offset of local header 4 bytes
  88.  
  89.         filename (variable size)
  90.         extra field (variable size)
  91.         file comment (variable size)
  92.  
  93.       End of central dir record:
  94.  
  95.         end of central dir signature    4 bytes  (0x06054b50)
  96.         number of this disk             2 bytes
  97.         number of the disk with the
  98.         start of the central directory  2 bytes
  99.         total number of entries in
  100.         the central dir on this disk    2 bytes
  101.         total number of entries in
  102.         the central dir                 2 bytes
  103.         size of the central directory   4 bytes
  104.         offset of start of central
  105.         directory with respect to
  106.         the starting disk number        4 bytes
  107.         zipfile comment length          2 bytes
  108.         zipfile comment (variable size)
  109.  
  110.  
  111.   D.  Explanation of fields:
  112.  
  113.       version made by (2 bytes)
  114.  
  115.           The upper byte indicates the compatibility of the file
  116.           attribute information.  If the external file attributes 
  117.           are compatible with MS-DOS and can be read by PKZIP for 
  118.           DOS version 2.04g then this value will be zero.  If these 
  119.           attributes are not compatible, then this value will identify 
  120.           the host system on which the attributes are compatible.
  121.           Software can use this information to determine the line 
  122.           record format for text files etc.  The current
  123.           mappings are:
  124.  
  125.           0 - MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems)
  126.           1 - Amiga                     2 - VAX/VMS
  127.           3 - Unix                      4 - VM/CMS
  128.           5 - Atari ST                  6 - OS/2 H.P.F.S.
  129.           7 - Macintosh                 8 - Z-System
  130.           9 - CP/M                     10 - Windows NTFS
  131.          11 thru 255 - unused
  132.  
  133.           The lower byte indicates the version number of the
  134.           software used to encode the file.  The value/10
  135.           indicates the major version number, and the value
  136.           mod 10 is the minor version number.
  137.  
  138.       version needed to extract (2 bytes)
  139.  
  140.           The minimum software version needed to extract the
  141.           file, mapped as above.
  142.  
  143.       general purpose bit flag: (2 bytes)
  144.  
  145.           Bit 0: If set, indicates that the file is encrypted.
  146.  
  147.           (For Method 6 - Imploding)
  148.           Bit 1: If the compression method used was type 6,
  149.                  Imploding, then this bit, if set, indicates
  150.                  an 8K sliding dictionary was used.  If clear,
  151.                  then a 4K sliding dictionary was used.
  152.           Bit 2: If the compression method used was type 6,
  153.                  Imploding, then this bit, if set, indicates
  154.                  an 3 Shannon-Fano trees were used to encode the
  155.                  sliding dictionary output.  If clear, then 2
  156.                  Shannon-Fano trees were used.
  157.  
  158.           (For Method 8 - Deflating)
  159.           Bit 2  Bit 1
  160.             0      0    Normal (-en) compression option was used.
  161.             0      1    Maximum (-ex) compression option was used.
  162.             1      0    Fast (-ef) compression option was used.
  163.             1      1    Super Fast (-es) compression option was used.
  164.  
  165.           Note:  Bits 1 and 2 are undefined if the compression
  166.                  method is any other.
  167.  
  168.           Bit 3: If this bit is set, the fields crc-32, compressed size
  169.                  and uncompressed size are set to zero in the local
  170.                  header.  The correct values are put in the data descriptor
  171.                  immediately following the compressed data.  (Note: PKZIP
  172.                  version 2.04g for DOS only recognizes this bit for method 8
  173.                  compression, newer versions of PKZIP recognize this bit
  174.                  for any compression method.)
  175.  
  176.           Bit 5: If this bit is set, this indicates that the file is compressed 
  177.                  patched data.(Note: Requires PKZIP version 2.70 or greater)
  178.  
  179.           The upper three bits are reserved and used internally
  180.           by the software when processing the zipfile.  The
  181.           remaining bits are unused.
  182.  
  183.       compression method: (2 bytes)
  184.  
  185.           (see accompanying documentation for algorithm
  186.           descriptions)
  187.  
  188.           0 - The file is stored (no compression)
  189.           1 - The file is Shrunk
  190.           2 - The file is Reduced with compression factor 1
  191.           3 - The file is Reduced with compression factor 2
  192.           4 - The file is Reduced with compression factor 3
  193.           5 - The file is Reduced with compression factor 4
  194.           6 - The file is Imploded
  195.           7 - Reserved for Tokenizing compression algorithm
  196.           8 - The file is Deflated
  197.           9 - Reserved for enhanced Deflating
  198.          10 - PKWARE Date Compression Library Imploding
  199.  
  200.       date and time fields: (2 bytes each)
  201.  
  202.           The date and time are encoded in standard MS-DOS format.
  203.           If input came from standard input, the date and time are
  204.           those at which compression was started for this data.
  205.  
  206.       CRC-32: (4 bytes)
  207.  
  208.           The CRC-32 algorithm was generously contributed by
  209.           David Schwaderer and can be found in his excellent
  210.           book "C Programmers Guide to NetBIOS" published by
  211.           Howard W. Sams & Co. Inc.  The 'magic number' for
  212.           the CRC is 0xdebb20e3.  The proper CRC pre and post
  213.           conditioning is used, meaning that the CRC register
  214.           is pre-conditioned with all ones (a starting value
  215.           of 0xffffffff) and the value is post-conditioned by
  216.           taking the one's complement of the CRC residual.
  217.           If bit 3 of the general purpose flag is set, this
  218.           field is set to zero in the local header and the correct
  219.           value is put in the data descriptor and in the central
  220.           directory.
  221.  
  222.       compressed size: (4 bytes)
  223.       uncompressed size: (4 bytes)
  224.  
  225.           The size of the file compressed and uncompressed,
  226.           respectively.  If bit 3 of the general purpose bit flag
  227.           is set, these fields are set to zero in the local header
  228.           and the correct values are put in the data descriptor and
  229.           in the central directory.
  230.  
  231.       filename length: (2 bytes)
  232.       extra field length: (2 bytes)
  233.       file comment length: (2 bytes)
  234.  
  235.           The length of the filename, extra field, and comment
  236.           fields respectively.  The combined length of any
  237.           directory record and these three fields should not
  238.           generally exceed 65,535 bytes.  If input came from standard
  239.           input, the filename length is set to zero.
  240.  
  241.  
  242.       disk number start: (2 bytes)
  243.  
  244.           The number of the disk on which this file begins.
  245.  
  246.       internal file attributes: (2 bytes)
  247.  
  248.           The lowest bit of this field indicates, if set, that
  249.           the file is apparently an ASCII or text file.  If not
  250.           set, that the file apparently contains binary data.
  251.           The remaining bits are unused in version 1.0.
  252.  
  253.       external file attributes: (4 bytes)
  254.  
  255.           The mapping of the external attributes is
  256.           host-system dependent (see 'version made by').  For
  257.           MS-DOS, the low order byte is the MS-DOS directory
  258.           attribute byte.  If input came from standard input, this
  259.           field is set to zero.
  260.  
  261.       relative offset of local header: (4 bytes)
  262.  
  263.           This is the offset from the start of the first disk on
  264.           which this file appears, to where the local header should
  265.           be found.
  266.  
  267.       filename: (Variable)
  268.  
  269.           The name of the file, with optional relative path.
  270.           The path stored should not contain a drive or
  271.           device letter, or a leading slash.  All slashes
  272.           should be forward slashes '/' as opposed to
  273.           backwards slashes '\' for compatibility with Amiga
  274.           and Unix file systems etc.  If input came from standard
  275.           input, there is no filename field.
  276.  
  277.       2: (Variable)
  278.  
  279.           This is for future expansion.  If additional information
  280.           needs to be stored in the future, it should be stored
  281.           here.  Earlier versions of the software can then safely
  282.           skip this file, and find the next file or header.  This
  283.           field will be 0 length in version 1.0.
  284.  
  285.           In order to allow different programs and different types
  286.           of information to be stored in the 'extra' field in .ZIP
  287.           files, the following structure should be used for all
  288.           programs storing data in this field:
  289.  
  290.           header1+data1 + header2+data2 . . .
  291.  
  292.           Each header should consist of:
  293.  
  294.             Header ID - 2 bytes
  295.             Data Size - 2 bytes
  296.  
  297.           Note: all fields stored in Intel low-byte/high-byte order.
  298.  
  299.           The Header ID field indicates the type of data that is in
  300.           the following data block.
  301.  
  302.           Header ID's of 0 thru 31 are reserved for use by PKWARE.
  303.           The remaining ID's can be used by third party vendors for
  304.           proprietary usage.
  305.  
  306.           The current Header ID mappings defined by PKWARE are:
  307.  
  308.           0x0007        AV Info
  309.           0x0009        OS/2
  310.           0x000c        VAX/VMS
  311.           0x000d        Unix
  312.           0x000f        Patch Descriptor
  313.  
  314.           Several third party mappings commonly used are:
  315.  
  316.           0x4b46        FWKCS MD5 (see below)
  317.           0x07c8        Macintosh
  318.           0x4341        Acorn/SparkFS 
  319.           0x4453        Windows NT security descriptor (binary ACL)
  320.           0x4704        VM/CMS
  321.           0x470f        MVS
  322.           0x4c41        OS/2 access control list (text ACL)
  323.           0x4d49        Info-ZIP VMS (VAX or Alpha)
  324.           0x5455        extended timestamp
  325.           0x5855        Info-ZIP Unix (original, also OS/2, NT, etc)
  326.           0x6542        BeOS/BeBox
  327.           0x756e        ASi Unix
  328.           0x7855        Info-ZIP Unix (new)
  329.           0xfd4a        SMS/QDOS
  330.  
  331.           The Data Size field indicates the size of the following
  332.           data block. Programs can use this value to skip to the
  333.           next header block, passing over any data blocks that are
  334.           not of interest.
  335.  
  336.           Note: As stated above, the size of the entire .ZIP file
  337.                 header, including the filename, comment, and extra
  338.                 field should not exceed 64K in size.
  339.  
  340.           In case two different programs should appropriate the same
  341.           Header ID value, it is strongly recommended that each
  342.           program place a unique signature of at least two bytes in
  343.           size (and preferably 4 bytes or bigger) at the start of
  344.           each data area.  Every program should verify that its
  345.           unique signature is present, in addition to the Header ID
  346.           value being correct, before assuming that it is a block of
  347.           known type.
  348.  
  349.  
  350.          -OS/2 Extra Field:
  351.  
  352.           The following is the layout of the OS/2 attributes "extra" block.
  353.           (Last Revision  09/05/95)
  354.  
  355.           Note: all fields stored in Intel low-byte/high-byte order.
  356.  
  357.  
  358.           Value         Size            Description
  359.           -----         ----            -----------
  360.   (OS/2)  0x0009        Short           Tag for this "extra" block type
  361.           TSize         Short           Size for the following data block
  362.           BSize         Long            Uncompressed Block Size
  363.           CType         Short           Compression type
  364.           EACRC         Long            CRC value for uncompress block
  365.           (var)         variable        Compressed block
  366.  
  367.  
  368.         The OS/2 extended attribute structure (FEA2LIST) is compressed and then stored
  369.         in it's entirety within this structure.  There will only ever be one "block" of data
  370.         in VarFields[].
  371.  
  372.  
  373.          -UNIX Extra Field:
  374.  
  375.           The following is the layout of the Unix "extra" block.
  376.           Note: all fields are stored in Intel low-byte/high-byte order.
  377.  
  378.  
  379.           Value         Size            Description
  380.           -----         ----            -----------
  381.   (UNIX)  0x000d        Short           Tag for this "extra" block type
  382.           TSize         Short           Size for the following data block
  383.           Atime         Long            File last access time
  384.           Mtime         Long            File last modification time
  385.           Uid           Short           File user ID
  386.           Gid           Short           File group ID
  387.           (var)         variable        Variable length data field
  388.  
  389.           The variable length data field will contain file type 
  390.           specific data.  Currently the only values allowed are
  391.           the original "linked to" file names for hard or symbolic links.
  392.  
  393.  
  394.          -VAX/VMS Extra Field:
  395.  
  396.           The following is the layout of the VAX/VMS attributes "extra"
  397.           block.
  398.  
  399.           Note: all fields stored in Intel low-byte/high-byte order.
  400.  
  401.           Value         Size            Description
  402.           -----         ----            -----------
  403.   (VMS)   0x000c        Short           Tag for this "extra" block type
  404.           TSize         Short           Size of the total "extra" block
  405.           CRC           Long            32-bit CRC for remainder of the block
  406.           Tag1          Short           VMS attribute tag value #1
  407.           Size1         Short           Size of attribute #1, in bytes
  408.           (var.)        Size1           Attribute #1 data
  409.           .
  410.           .
  411.           .
  412.           TagN          Short           VMS attribute tage value #N
  413.           SizeN         Short           Size of attribute #N, in bytes
  414.           (var.)        SizeN           Attribute #N data
  415.  
  416.           Rules:
  417.  
  418.           1. There will be one or more of attributes present, which will
  419.              each be preceded by the above TagX & SizeX values.  These
  420.              values are identical to the ATR$C_XXXX and ATR$S_XXXX constants
  421.              which are defined in ATR.H under VMS C.  Neither of these values
  422.              will ever be zero.
  423.  
  424.           2. No word alignment or padding is performed.
  425.  
  426.           3. A well-behaved PKZIP/VMS program should never produce more than
  427.              one sub-block with the same TagX value.  Also, there will never
  428.              be more than one "extra" block of type 0x000c in a particular
  429.              directory record.
  430.  
  431.  
  432.          -PATCH Descriptor Extra Field:
  433.  
  434.           The following is the layout of the Patch Descriptor "extra"
  435.           block.
  436.  
  437.           Note: all fields stored in Intel low-byte/high-byte order.
  438.  
  439.           Value         Size            Description
  440.           -----         ----            -----------
  441.   (Patch) 0x000f        Short           Tag for this "extra" block type
  442.           TSize         Short           Size of the total "extra" block
  443.           Version       Short           Version of the descriptor
  444.           Flags         Long            Actions and reactions (see below) 
  445.           OldSize       Long            Size of the file about to be patched 
  446.           OldCRC        Long            32-bit CRC of the file about to be patched 
  447.           NewSize       Long            Size of the resulting file 
  448.           NewCRC        Long            32-bit CRC of the resulting file 
  449.  
  450.  
  451.           Actions and reactions
  452.  
  453.           Bits          Description
  454.           ----          ----------------
  455.           0             Use for autodetection
  456.           1             Treat as selfpatch
  457.           2-3           RESERVED
  458.           4-5           Action (see below)
  459.           6-7           RESERVED
  460.           8-9           Reaction (see below) to absent file 
  461.           10-11         Reaction (see below) to newer file
  462.           12-13         Reaction (see below) to unknown file
  463.           14-15         RESERVED
  464.           16-31         RESERVED
  465.  
  466.           Actions
  467.  
  468.           Action       Value
  469.           ------       ----- 
  470.           none         0
  471.           add          1
  472.           delete       2
  473.           patch        3
  474.  
  475.           Reactions
  476.  
  477.           Reaction     Value
  478.           --------     -----
  479.           ask          0
  480.           skip         1
  481.           ignore       2
  482.           fail         3
  483.  
  484.  
  485.           - FWKCS MD5 Extra Field:
  486.  
  487.           The FWKCS Contents_Signature System, used in
  488.           automatically identifying files independent of filename,
  489.           optionally adds and uses an extra field to support the
  490.           rapid creation of an enhanced contents_signature:
  491.  
  492.               Header ID = 0x4b46
  493.               Data Size = 0x0013
  494.               Preface   = 'M','D','5'
  495.               followed by 16 bytes containing the uncompressed
  496.                   file's 128_bit MD5 hash(1), low byte first.
  497.  
  498.           When FWKCS revises a zipfile central directory to add
  499.           this extra field for a file, it also replaces the
  500.           central directory entry for that file's uncompressed
  501.           filelength with a measured value.
  502.  
  503.           FWKCS provides an option to strip this extra field, if
  504.           present, from a zipfile central directory. In adding
  505.           this extra field, FWKCS preserves Zipfile Authenticity
  506.           Verification; if stripping this extra field, FWKCS
  507.           preserves all versions of AV through PKZIP version 2.04g.
  508.  
  509.           FWKCS, and FWKCS Contents_Signature System, are
  510.           trademarks of Frederick W. Kantor.
  511.  
  512.           (1) R. Rivest, RFC1321.TXT, MIT Laboratory for Computer
  513.               Science and RSA Data Security, Inc., April 1992.
  514.               ll.76-77: "The MD5 algorithm is being placed in the
  515.               public domain for review and possible adoption as a
  516.               standard."
  517.  
  518.       file comment: (Variable)
  519.  
  520.           The comment for this file.
  521.  
  522.       number of this disk: (2 bytes)
  523.  
  524.           The number of this disk, which contains central
  525.           directory end record.
  526.  
  527.       number of the disk with the start of the central directory: (2 bytes)
  528.  
  529.           The number of the disk on which the central
  530.           directory starts.
  531.  
  532.       total number of entries in the central dir on this disk: (2 bytes)
  533.  
  534.           The number of central directory entries on this disk.
  535.  
  536.       total number of entries in the central dir: (2 bytes)
  537.  
  538.           The total number of files in the zipfile.
  539.  
  540.  
  541.       size of the central directory: (4 bytes)
  542.  
  543.           The size (in bytes) of the entire central directory.
  544.  
  545.       offset of start of central directory with respect to
  546.       the starting disk number:  (4 bytes)
  547.  
  548.           Offset of the start of the central directory on the
  549.           disk on which the central directory starts.
  550.  
  551.       zipfile comment length: (2 bytes)
  552.  
  553.           The length of the comment for this zipfile.
  554.  
  555.       zipfile comment: (Variable)
  556.  
  557.           The comment for this zipfile.
  558.  
  559.  
  560.   D.  General notes:
  561.  
  562.       1)  All fields unless otherwise noted are unsigned and stored
  563.           in Intel low-byte:high-byte, low-word:high-word order.
  564.  
  565.       2)  String fields are not null terminated, since the
  566.           length is given explicitly.
  567.  
  568.       3)  Local headers should not span disk boundaries.  Also, even
  569.           though the central directory can span disk boundaries, no
  570.           single record in the central directory should be split
  571.           across disks.
  572.  
  573.       4)  The entries in the central directory may not necessarily
  574.           be in the same order that files appear in the zipfile.
  575.  
  576. UnShrinking - Method 1
  577. ----------------------
  578.  
  579. Shrinking is a Dynamic Ziv-Lempel-Welch compression algorithm
  580. with partial clearing.  The initial code size is 9 bits, and
  581. the maximum code size is 13 bits.  Shrinking differs from
  582. conventional Dynamic Ziv-Lempel-Welch implementations in several
  583. respects:
  584.  
  585. 1)  The code size is controlled by the compressor, and is not
  586.     automatically increased when codes larger than the current
  587.     code size are created (but not necessarily used).  When
  588.     the decompressor encounters the code sequence 256
  589.     (decimal) followed by 1, it should increase the code size
  590.     read from the input stream to the next bit size.  No
  591.     blocking of the codes is performed, so the next code at
  592.     the increased size should be read from the input stream
  593.     immediately after where the previous code at the smaller
  594.     bit size was read.  Again, the decompressor should not
  595.     increase the code size used until the sequence 256,1 is
  596.     encountered.
  597.  
  598. 2)  When the table becomes full, total clearing is not
  599.     performed.  Rather, when the compressor emits the code
  600.     sequence 256,2 (decimal), the decompressor should clear
  601.     all leaf nodes from the Ziv-Lempel tree, and continue to
  602.     use the current code size.  The nodes that are cleared
  603.     from the Ziv-Lempel tree are then re-used, with the lowest
  604.     code value re-used first, and the highest code value
  605.     re-used last.  The compressor can emit the sequence 256,2
  606.     at any time.
  607.  
  608.  
  609.  
  610. Expanding - Methods 2-5
  611. -----------------------
  612.  
  613. The Reducing algorithm is actually a combination of two
  614. distinct algorithms.  The first algorithm compresses repeated
  615. byte sequences, and the second algorithm takes the compressed
  616. stream from the first algorithm and applies a probabilistic
  617. compression method.
  618.  
  619. The probabilistic compression stores an array of 'follower
  620. sets' S(j), for j=0 to 255, corresponding to each possible
  621. ASCII character.  Each set contains between 0 and 32
  622. characters, to be denoted as S(j)[0],...,S(j)[m], where m<32.
  623. The sets are stored at the beginning of the data area for a
  624. Reduced file, in reverse order, with S(255) first, and S(0)
  625. last.
  626.  
  627. The sets are encoded as { N(j), S(j)[0],...,S(j)[N(j)-1] },
  628. where N(j) is the size of set S(j).  N(j) can be 0, in which
  629. case the follower set for S(j) is empty.  Each N(j) value is
  630. encoded in 6 bits, followed by N(j) eight bit character values
  631. corresponding to S(j)[0] to S(j)[N(j)-1] respectively.  If
  632. N(j) is 0, then no values for S(j) are stored, and the value
  633. for N(j-1) immediately follows.
  634.  
  635. Immediately after the follower sets, is the compressed data
  636. stream.  The compressed data stream can be interpreted for the
  637. probabilistic decompression as follows:
  638.  
  639.  
  640. let Last-Character <- 0.
  641. loop until done
  642.     if the follower set S(Last-Character) is empty then
  643.         read 8 bits from the input stream, and copy this
  644.         value to the output stream.
  645.     otherwise if the follower set S(Last-Character) is non-empty then
  646.         read 1 bit from the input stream.
  647.         if this bit is not zero then
  648.             read 8 bits from the input stream, and copy this
  649.             value to the output stream.
  650.         otherwise if this bit is zero then
  651.             read B(N(Last-Character)) bits from the input
  652.             stream, and assign this value to I.
  653.             Copy the value of S(Last-Character)[I] to the
  654.             output stream.
  655.  
  656.     assign the last value placed on the output stream to
  657.     Last-Character.
  658. end loop
  659.  
  660.  
  661. B(N(j)) is defined as the minimal number of bits required to
  662. encode the value N(j)-1.
  663.  
  664.  
  665. The decompressed stream from above can then be expanded to
  666. re-create the original file as follows:
  667.  
  668.  
  669. let State <- 0.
  670.  
  671. loop until done
  672.     read 8 bits from the input stream into C.
  673.     case State of
  674.         0:  if C is not equal to DLE (144 decimal) then
  675.                 copy C to the output stream.
  676.             otherwise if C is equal to DLE then
  677.                 let State <- 1.
  678.  
  679.         1:  if C is non-zero then
  680.                 let V <- C.
  681.                 let Len <- L(V)
  682.                 let State <- F(Len).
  683.             otherwise if C is zero then
  684.                 copy the value 144 (decimal) to the output stream.
  685.                 let State <- 0
  686.  
  687.         2:  let Len <- Len + C
  688.             let State <- 3.
  689.  
  690.         3:  move backwards D(V,C) bytes in the output stream
  691.             (if this position is before the start of the output
  692.             stream, then assume that all the data before the
  693.             start of the output stream is filled with zeros).
  694.             copy Len+3 bytes from this position to the output stream.
  695.             let State <- 0.
  696.     end case
  697. end loop
  698.  
  699.  
  700. The functions F,L, and D are dependent on the 'compression
  701. factor', 1 through 4, and are defined as follows:
  702.  
  703. For compression factor 1:
  704.     L(X) equals the lower 7 bits of X.
  705.     F(X) equals 2 if X equals 127 otherwise F(X) equals 3.
  706.     D(X,Y) equals the (upper 1 bit of X) * 256 + Y + 1.
  707. For compression factor 2:
  708.     L(X) equals the lower 6 bits of X.
  709.     F(X) equals 2 if X equals 63 otherwise F(X) equals 3.
  710.     D(X,Y) equals the (upper 2 bits of X) * 256 + Y + 1.
  711. For compression factor 3:
  712.     L(X) equals the lower 5 bits of X.
  713.     F(X) equals 2 if X equals 31 otherwise F(X) equals 3.
  714.     D(X,Y) equals the (upper 3 bits of X) * 256 + Y + 1.
  715. For compression factor 4:
  716.     L(X) equals the lower 4 bits of X.
  717.     F(X) equals 2 if X equals 15 otherwise F(X) equals 3.
  718.     D(X,Y) equals the (upper 4 bits of X) * 256 + Y + 1.
  719.  
  720.  
  721. Imploding - Method 6
  722. --------------------
  723.  
  724. The Imploding algorithm is actually a combination of two distinct
  725. algorithms.  The first algorithm compresses repeated byte
  726. sequences using a sliding dictionary.  The second algorithm is
  727. used to compress the encoding of the sliding dictionary output,
  728. using multiple Shannon-Fano trees.
  729.  
  730. The Imploding algorithm can use a 4K or 8K sliding dictionary
  731. size. The dictionary size used can be determined by bit 1 in the
  732. general purpose flag word; a 0 bit indicates a 4K dictionary
  733. while a 1 bit indicates an 8K dictionary.
  734.  
  735. The Shannon-Fano trees are stored at the start of the compressed
  736. file. The number of trees stored is defined by bit 2 in the
  737. general purpose flag word; a 0 bit indicates two trees stored, a
  738. 1 bit indicates three trees are stored.  If 3 trees are stored,
  739. the first Shannon-Fano tree represents the encoding of the
  740. Literal characters, the second tree represents the encoding of
  741. the Length information, the third represents the encoding of the
  742. Distance information.  When 2 Shannon-Fano trees are stored, the
  743. Length tree is stored first, followed by the Distance tree.
  744.  
  745. The Literal Shannon-Fano tree, if present is used to represent
  746. the entire ASCII character set, and contains 256 values.  This
  747. tree is used to compress any data not compressed by the sliding
  748. dictionary algorithm.  When this tree is present, the Minimum
  749. Match Length for the sliding dictionary is 3.  If this tree is
  750. not present, the Minimum Match Length is 2.
  751.  
  752. The Length Shannon-Fano tree is used to compress the Length part
  753. of the (length,distance) pairs from the sliding dictionary
  754. output.  The Length tree contains 64 values, ranging from the
  755. Minimum Match Length, to 63 plus the Minimum Match Length.
  756.  
  757. The Distance Shannon-Fano tree is used to compress the Distance
  758. part of the (length,distance) pairs from the sliding dictionary
  759. output. The Distance tree contains 64 values, ranging from 0 to
  760. 63, representing the upper 6 bits of the distance value.  The
  761. distance values themselves will be between 0 and the sliding
  762. dictionary size, either 4K or 8K.
  763.  
  764. The Shannon-Fano trees themselves are stored in a compressed
  765. format. The first byte of the tree data represents the number of
  766. bytes of data representing the (compressed) Shannon-Fano tree
  767. minus 1.  The remaining bytes represent the Shannon-Fano tree
  768. data encoded as:
  769.  
  770.     High 4 bits: Number of values at this bit length + 1. (1 - 16)
  771.     Low  4 bits: Bit Length needed to represent value + 1. (1 - 16)
  772.  
  773. The Shannon-Fano codes can be constructed from the bit lengths
  774. using the following algorithm:
  775.  
  776. 1)  Sort the Bit Lengths in ascending order, while retaining the
  777.     order of the original lengths stored in the file.
  778.  
  779. 2)  Generate the Shannon-Fano trees:
  780.  
  781.     Code <- 0
  782.     CodeIncrement <- 0
  783.     LastBitLength <- 0
  784.     i <- number of Shannon-Fano codes - 1   (either 255 or 63)
  785.  
  786.     loop while i >= 0
  787.         Code = Code + CodeIncrement
  788.         if BitLength(i) <> LastBitLength then
  789.             LastBitLength=BitLength(i)
  790.             CodeIncrement = 1 shifted left (16 - LastBitLength)
  791.         ShannonCode(i) = Code
  792.         i <- i - 1
  793.     end loop
  794.  
  795.  
  796. 3)  Reverse the order of all the bits in the above ShannonCode()
  797.     vector, so that the most significant bit becomes the least
  798.     significant bit.  For example, the value 0x1234 (hex) would
  799.     become 0x2C48 (hex).
  800.  
  801. 4)  Restore the order of Shannon-Fano codes as originally stored
  802.     within the file.
  803.  
  804. Example:
  805.  
  806.     This example will show the encoding of a Shannon-Fano tree
  807.     of size 8.  Notice that the actual Shannon-Fano trees used
  808.     for Imploding are either 64 or 256 entries in size.
  809.  
  810. Example:   0x02, 0x42, 0x01, 0x13
  811.  
  812.     The first byte indicates 3 values in this table.  Decoding the
  813.     bytes:
  814.             0x42 = 5 codes of 3 bits long
  815.             0x01 = 1 code  of 2 bits long
  816.             0x13 = 2 codes of 4 bits long
  817.  
  818.     This would generate the original bit length array of:
  819.     (3, 3, 3, 3, 3, 2, 4, 4)
  820.  
  821.     There are 8 codes in this table for the values 0 thru 7.  Using the
  822.     algorithm to obtain the Shannon-Fano codes produces:
  823.  
  824.                                   Reversed     Order     Original
  825. Val  Sorted   Constructed Code      Value     Restored    Length
  826. ---  ------   -----------------   --------    --------    ------
  827. 0:     2      1100000000000000        11       101          3
  828. 1:     3      1010000000000000       101       001          3
  829. 2:     3      1000000000000000       001       110          3
  830. 3:     3      0110000000000000       110       010          3
  831. 4:     3      0100000000000000       010       100          3
  832. 5:     3      0010000000000000       100        11          2
  833. 6:     4      0001000000000000      1000      1000          4
  834. 7:     4      0000000000000000      0000      0000          4
  835.  
  836.  
  837. The values in the Val, Order Restored and Original Length columns
  838. now represent the Shannon-Fano encoding tree that can be used for
  839. decoding the Shannon-Fano encoded data.  How to parse the
  840. variable length Shannon-Fano values from the data stream is beyond the
  841. scope of this document.  (See the references listed at the end of
  842. this document for more information.)  However, traditional decoding
  843. schemes used for Huffman variable length decoding, such as the
  844. Greenlaw algorithm, can be successfully applied.
  845.  
  846. The compressed data stream begins immediately after the
  847. compressed Shannon-Fano data.  The compressed data stream can be
  848. interpreted as follows:
  849.  
  850. loop until done
  851.     read 1 bit from input stream.
  852.  
  853.     if this bit is non-zero then       (encoded data is literal data)
  854.         if Literal Shannon-Fano tree is present
  855.             read and decode character using Literal Shannon-Fano tree.
  856.         otherwise
  857.             read 8 bits from input stream.
  858.         copy character to the output stream.
  859.     otherwise                   (encoded data is sliding dictionary match)
  860.         if 8K dictionary size
  861.             read 7 bits for offset Distance (lower 7 bits of offset).
  862.         otherwise
  863.             read 6 bits for offset Distance (lower 6 bits of offset).
  864.  
  865.         using the Distance Shannon-Fano tree, read and decode the
  866.           upper 6 bits of the Distance value.
  867.  
  868.         using the Length Shannon-Fano tree, read and decode
  869.           the Length value.
  870.  
  871.         Length <- Length + Minimum Match Length
  872.  
  873.         if Length = 63 + Minimum Match Length
  874.             read 8 bits from the input stream,
  875.             add this value to Length.
  876.  
  877.         move backwards Distance+1 bytes in the output stream, and
  878.         copy Length characters from this position to the output
  879.         stream.  (if this position is before the start of the output
  880.         stream, then assume that all the data before the start of
  881.         the output stream is filled with zeros).
  882. end loop
  883.  
  884. Tokenizing - Method 7
  885. --------------------
  886.  
  887. This method is not used by PKZIP.
  888.  
  889. Deflating - Method 8
  890. -----------------
  891.  
  892. The Deflate algorithm is similar to the Implode algorithm using
  893. a sliding dictionary of up to 32K with secondary compression
  894. from Huffman/Shannon-Fano codes.
  895.  
  896. The compressed data is stored in blocks with a header describing
  897. the block and the Huffman codes used in the data block.  The header
  898. format is as follows:
  899.  
  900.    Bit 0: Last Block bit     This bit is set to 1 if this is the last
  901.                              compressed block in the data.
  902.    Bits 1-2: Block type
  903.       00 (0) - Block is stored - All stored data is byte aligned.
  904.                Skip bits until next byte, then next word = block length,
  905.                followed by the ones compliment of the block length word.
  906.                Remaining data in block is the stored data.
  907.  
  908.       01 (1) - Use fixed Huffman codes for literal and distance codes.
  909.                Lit Code    Bits             Dist Code   Bits
  910.                ---------   ----             ---------   ----
  911.                  0 - 143    8                 0 - 31      5
  912.                144 - 255    9
  913.                256 - 279    7
  914.                280 - 287    8
  915.  
  916.                Literal codes 286-287 and distance codes 30-31 are never
  917.                used but participate in the huffman construction.
  918.  
  919.       10 (2) - Dynamic Huffman codes.  (See expanding Huffman codes)
  920.  
  921.       11 (3) - Reserved - Flag a "Error in compressed data" if seen.
  922.  
  923. Expanding Huffman Codes
  924. -----------------------
  925. If the data block is stored with dynamic Huffman codes, the Huffman
  926. codes are sent in the following compressed format:
  927.  
  928.    5 Bits: # of Literal codes sent - 256 (256 - 286)
  929.            All other codes are never sent.
  930.    5 Bits: # of Dist codes - 1           (1 - 32)
  931.    4 Bits: # of Bit Length codes - 3     (3 - 19)
  932.  
  933. The Huffman codes are sent as bit lengths and the codes are built as
  934. described in the implode algorithm.  The bit lengths themselves are
  935. compressed with Huffman codes.  There are 19 bit length codes:
  936.  
  937.    0 - 15: Represent bit lengths of 0 - 15
  938.        16: Copy the previous bit length 3 - 6 times.
  939.            The next 2 bits indicate repeat length (0 = 3, ... ,3 = 6)
  940.               Example:  Codes 8, 16 (+2 bits 11), 16 (+2 bits 10) will
  941.                         expand to 12 bit lengths of 8 (1 + 6 + 5)
  942.        17: Repeat a bit length of 0 for 3 - 10 times. (3 bits of length)
  943.        18: Repeat a bit length of 0 for 11 - 138 times (7 bits of length)
  944.  
  945. The lengths of the bit length codes are sent packed 3 bits per value
  946. (0 - 7) in the following order:
  947.  
  948.    16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  949.  
  950. The Huffman codes should be built as described in the Implode algorithm
  951. except codes are assigned starting at the shortest bit length, i.e. the
  952. shortest code should be all 0's rather than all 1's.  Also, codes with
  953. a bit length of zero do not participate in the tree construction.  The
  954. codes are then used to decode the bit lengths for the literal and distance
  955. tables.
  956.  
  957. The bit lengths for the literal tables are sent first with the number
  958. of entries sent described by the 5 bits sent earlier.  There are up
  959. to 286 literal characters; the first 256 represent the respective 8
  960. bit character, code 256 represents the End-Of-Block code, the remaining
  961. 29 codes represent copy lengths of 3 thru 258.  There are up to 30
  962. distance codes representing distances from 1 thru 32k as described
  963. below.
  964.  
  965.                              Length Codes
  966.                              ------------
  967.       Extra             Extra              Extra              Extra
  968.  Code Bits Length  Code Bits Lengths  Code Bits Lengths  Code Bits Length(s)
  969.  ---- ---- ------  ---- ---- -------  ---- ---- -------  ---- ---- ---------
  970.   257   0     3     265   1   11,12    273   3   35-42    281   5  131-162
  971.   258   0     4     266   1   13,14    274   3   43-50    282   5  163-194
  972.   259   0     5     267   1   15,16    275   3   51-58    283   5  195-226
  973.   260   0     6     268   1   17,18    276   3   59-66    284   5  227-257
  974.   261   0     7     269   2   19-22    277   4   67-82    285   0    258
  975.   262   0     8     270   2   23-26    278   4   83-98
  976.   263   0     9     271   2   27-30    279   4   99-114
  977.   264   0    10     272   2   31-34    280   4  115-130
  978.  
  979.                             Distance Codes
  980.                             --------------
  981.       Extra           Extra             Extra               Extra
  982.  Code Bits Dist  Code Bits  Dist   Code Bits Distance  Code Bits Distance
  983.  ---- ---- ----  ---- ---- ------  ---- ---- --------  ---- ---- --------
  984.    0   0    1      8   3   17-24    16    7  257-384    24   11  4097-6144
  985.    1   0    2      9   3   25-32    17    7  385-512    25   11  6145-8192
  986.    2   0    3     10   4   33-48    18    8  513-768    26   12  8193-12288
  987.    3   0    4     11   4   49-64    19    8  769-1024   27   12 12289-16384
  988.    4   1   5,6    12   5   65-96    20    9 1025-1536   28   13 16385-24576
  989.    5   1   7,8    13   5   97-128   21    9 1537-2048   29   13 24577-32768
  990.    6   2   9-12   14   6  129-192   22   10 2049-3072
  991.    7   2  13-16   15   6  193-256   23   10 3073-4096
  992.  
  993. The compressed data stream begins immediately after the
  994. compressed header data.  The compressed data stream can be
  995. interpreted as follows:
  996.  
  997. do
  998.    read header from input stream.
  999.  
  1000.    if stored block
  1001.       skip bits until byte aligned
  1002.       read count and 1's compliment of count
  1003.       copy count bytes data block
  1004.    otherwise
  1005.       loop until end of block code sent
  1006.          decode literal character from input stream
  1007.          if literal < 256
  1008.             copy character to the output stream
  1009.          otherwise
  1010.             if literal = end of block
  1011.                break from loop
  1012.             otherwise
  1013.                decode distance from input stream
  1014.  
  1015.                move backwards distance bytes in the output stream, and
  1016.                copy length characters from this position to the output
  1017.                stream.
  1018.       end loop
  1019. while not last block
  1020.  
  1021. if data descriptor exists
  1022.    skip bits until byte aligned
  1023.    read crc and sizes
  1024. endif
  1025.  
  1026. Decryption
  1027. ----------
  1028.  
  1029. The encryption used in PKZIP was generously supplied by Roger
  1030. Schlafly.  PKWARE is grateful to Mr. Schlafly for his expert
  1031. help and advice in the field of data encryption.
  1032.  
  1033. PKZIP encrypts the compressed data stream.  Encrypted files must
  1034. be decrypted before they can be extracted.
  1035.  
  1036. Each encrypted file has an extra 12 bytes stored at the start of
  1037. the data area defining the encryption header for that file.  The
  1038. encryption header is originally set to random values, and then
  1039. itself encrypted, using three, 32-bit keys.  The key values are
  1040. initialized using the supplied encryption password.  After each byte
  1041. is encrypted, the keys are then updated using pseudo-random number
  1042. generation techniques in combination with the same CRC-32 algorithm
  1043. used in PKZIP and described elsewhere in this document.
  1044.  
  1045. The following is the basic steps required to decrypt a file:
  1046.  
  1047. 1) Initialize the three 32-bit keys with the password.
  1048. 2) Read and decrypt the 12-byte encryption header, further
  1049.    initializing the encryption keys.
  1050. 3) Read and decrypt the compressed data stream using the
  1051.    encryption keys.
  1052.  
  1053.  
  1054. Step 1 - Initializing the encryption keys
  1055. -----------------------------------------
  1056.  
  1057. Key(0) <- 305419896
  1058. Key(1) <- 591751049
  1059. Key(2) <- 878082192
  1060.  
  1061. loop for i <- 0 to length(password)-1
  1062.     update_keys(password(i))
  1063. end loop
  1064.  
  1065.  
  1066. Where update_keys() is defined as:
  1067.  
  1068.  
  1069. update_keys(char):
  1070.   Key(0) <- crc32(key(0),char)
  1071.   Key(1) <- Key(1) + (Key(0) & 000000ffH)
  1072.   Key(1) <- Key(1) * 134775813 + 1
  1073.   Key(2) <- crc32(key(2),key(1) >> 24)
  1074. end update_keys
  1075.  
  1076.  
  1077. Where crc32(old_crc,char) is a routine that given a CRC value and a
  1078. character, returns an updated CRC value after applying the CRC-32
  1079. algorithm described elsewhere in this document.
  1080.  
  1081.  
  1082. Step 2 - Decrypting the encryption header
  1083. -----------------------------------------
  1084.  
  1085. The purpose of this step is to further initialize the encryption
  1086. keys, based on random data, to render a plaintext attack on the
  1087. data ineffective.
  1088.  
  1089.  
  1090. Read the 12-byte encryption header into Buffer, in locations
  1091. Buffer(0) thru Buffer(11).
  1092.  
  1093. loop for i <- 0 to 11
  1094.     C <- buffer(i) ^ decrypt_byte()
  1095.     update_keys(C)
  1096.     buffer(i) <- C
  1097. end loop
  1098.  
  1099.  
  1100. Where decrypt_byte() is defined as:
  1101.  
  1102.  
  1103. unsigned char decrypt_byte()
  1104.     local unsigned short temp
  1105.     temp <- Key(2) | 2
  1106.     decrypt_byte <- (temp * (temp ^ 1)) >> 8
  1107. end decrypt_byte
  1108.  
  1109.  
  1110. After the header is decrypted,  the last 1 or 2 bytes in Buffer
  1111. should be the high-order word/byte of the CRC for the file being
  1112. decrypted, stored in Intel low-byte/high-byte order.  Versions of
  1113. PKZIP prior to 2.0 used a 2 byte CRC check; a 1 byte CRC check is
  1114. used on versions after 2.0.  This can be used to test if the password
  1115. supplied is correct or not.
  1116.  
  1117.  
  1118. Step 3 - Decrypting the compressed data stream
  1119. ----------------------------------------------
  1120.  
  1121. The compressed data stream can be decrypted as follows:
  1122.  
  1123.  
  1124. loop until done
  1125.     read a character into C
  1126.     Temp <- C ^ decrypt_byte()
  1127.     update_keys(temp)
  1128.     output Temp
  1129. end loop
  1130.  
  1131.  
  1132. In addition to the above mentioned contributors to PKZIP and PKUNZIP,
  1133. I would like to extend special thanks to Robert Mahoney for suggesting
  1134. the extension .ZIP for this software.
  1135.  
  1136.  
  1137. References:
  1138.  
  1139.     Fiala, Edward R., and Greene, Daniel H., "Data compression with
  1140.        finite windows",  Communications of the ACM, Volume 32, Number 4,
  1141.        April 1989, pages 490-505.
  1142.  
  1143.     Held, Gilbert, "Data Compression, Techniques and Applications,
  1144.                     Hardware and Software Considerations",
  1145.        John Wiley & Sons, 1987.
  1146.  
  1147.     Huffman, D.A., "A method for the construction of minimum-redundancy
  1148.        codes", Proceedings of the IRE, Volume 40, Number 9, September 1952,
  1149.        pages 1098-1101.
  1150.  
  1151.     Nelson, Mark, "LZW Data Compression", Dr. Dobbs Journal, Volume 14,
  1152.        Number 10, October 1989, pages 29-37.
  1153.  
  1154.     Nelson, Mark, "The Data Compression Book",  M&T Books, 1991.
  1155.  
  1156.     Storer, James A., "Data Compression, Methods and Theory",
  1157.        Computer Science Press, 1988
  1158.  
  1159.     Welch, Terry, "A Technique for High-Performance Data Compression",
  1160.        IEEE Computer, Volume 17, Number 6, June 1984, pages 8-19.
  1161.  
  1162.     Ziv, J. and Lempel, A., "A universal algorithm for sequential data
  1163.        compression", Communications of the ACM, Volume 30, Number 6,
  1164.        June 1987, pages 520-540.
  1165.  
  1166.     Ziv, J. and Lempel, A., "Compression of individual sequences via
  1167.        variable-rate coding", IEEE Transactions on Information Theory,
  1168.        Volume 24, Number 5, September 1978, pages 530-536.
  1169.